﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HiStaff.Util;
using HiStaff.Base;
using HiStaff.Control;
using HiStaff.Dal;
using HiStaff.Domain.CO;
using HiStaff.Util.Enum;
using Janus.Windows.UI.CommandBars;
using Janus.Windows.GridEX;
using System.Globalization;
namespace HiStaff.iTime
{
    public partial class SwipeDataSummary : FormBase
    {
        private List<CO_COLOR_OBJECT> DataColor;
        private List<ERP_SY_ORGPERIOD> _lstOrgPeriod;
        private DataView dwDataPrepare;
        //private frmSwipeDateRangeImport frmImpRange;
        private bool _isOverrideData = true;

        private const string DTCOL_UPDATE = "UPDATE";
        private const string DTCOL_TRUEVALUE = "TRUEVALUE";

        private const string TCMD_YEAR = "YEAR";
        private const string DDCMD_TIMEPERIOD = "TIMEPERIOD";
        private const string DDCMD_SITE = "SITE";

        private const string GCOL_SELECTOR = "SELECTOR";
        private const string GCOL_EMPLOYEEID = "EMPLOYEEID";
        private const string GCOL_EMPLOYEENAME = "EMPLOYEENAME";
        private const string GCOL_ORGNAME = "ORGNAME";
        private const string GCOL_WORKINGDAY = "WORKINGDAY";
        private const string GCOL_PREFIX_DATA_VALIN = "VALIN";
        private const string GCOL_PREFIX_DATA_VALOUT = "VALOUT";
        private const string GCOL_PREFIX_CAPTION_VALIN = "VÀO ";
        private const string GCOL_PREFIX_CAPTION_VALOUT = "RA ";
        private const string GCOL_SUNDAY = "SUNDAY";
        private const string GCOL_ID = "ID";
        private const string GCOL_STATUS = "STATUS";

        private const string FILLTER_EMPWRKALL = "Column2='{0}' AND Column4=#{1}# AND " + DTCOL_UPDATE + "=0";
        private const string FILLTER_EMPWRK = "Column2='{0}' AND (Column4=#{1}# OR Column4=#{2}#)AND " + DTCOL_UPDATE + "=0";
        private const string COMMAND_UPDATEVALUE = ",{0}=TO_DATE('{1}','DD/MM/YYYY HH24:MI')";
        private const string COMMAND_UPDATENULLVALUE = ",{0}=NULL";
        private const string MSG_INVALID_PERIOD = "Dữ liệu trong tệp không phù hợp với kỳ công tương ứng, không thể thực hiện việc đăng ký dữ liệu.\nVui lòng kiểm tra lại.";
        private const string MSG_PROCESSING_RECORDS = "Đang kiểm tra dữ liệu của nhân viên: {0}({1})/[{2}%]";
        private const string MSG_UPDATE_RECORDS = "Đang cập nhật dữ liệu của nhân viên: {0}({1})/[{2}%]";

        public SwipeDataSummary()
        {
            InitializeComponent();
            //ucOrgTreeview.Username = StaticObject.Username;
        }

        private void frmSwipeDataSummary_Load(object sender, EventArgs e)
        {
            try
            {
                if (IsProcessing)
                {
                    return;
                }
                else
                {
                    IsProcessing = true;
                }

               // ucOrgTreeview.TreeViewAfterSelect += new TreeViewAfterSelectHandler(ucOrgTreeview_TreeViewAfterSelect);

                base.CreateDropdownInCommandBar(DDCMD_SITE, "Site", 90, 15);

                base.CreateTxtInCommandBar(TCMD_YEAR, "Năm", 40, DateTime.Now.Year.ToString());

                base.CreateDropdownInCommandBar(DDCMD_TIMEPERIOD, "Kỳ công", 80, 12);

                base.CreateCommandBar(//CommandBarManager.ActionCommand.ImportAnotherFile,
                                      CommandBarManager.ActionCommand.ImportExcel,
                                      CommandBarManager.ActionCommand.New,
                                      CommandBarManager.ActionCommand.Separator,
                                      CommandBarManager.ActionCommand.Save,
                                      CommandBarManager.ActionCommand.Separator,
                                      CommandBarManager.ActionCommand.Delete,
                                      CommandBarManager.ActionCommand.Separator,
                                      CommandBarManager.ActionCommand.Exit);
                LoadSite();

                InitGrid();

                LoadTimePeriodByOrg(DateTime.Now.Year);

                VisibleProgressBar = true;
                VisibleStatusTextBar = true;
                SetProgressBar(0);
                SetStatusText(string.Empty, MessageIcon.Null);

                LoadGridData(false);

                IsProcessing = false;

            }
            catch (Exception ex)
            {
                IsProcessing = false;
                MessageBox.Show(ex.Message + ex.StackTrace);
                Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
        }
        private void LoadSite()
        {
            var lstData = OracleHelper.ExcuteSelectMultiObject<erp_sy_organizationDuty>("pkg_hcm_list", "PRS_TREEORGDUTY",
                    new erp_sy_organizationDuty {
                       
                        //Username = StaticObject.Username 
                    });
            base.SetDataSourceToDropdownCommand(DDCMD_SITE, lstData, "DVN_NAME", "DORG_ID", true);
            UICommand command = base.GetCommandByKey(DDCMD_SITE);

            if (command.GetUIComboBox().Items.Count > 0)
                command.GetUIComboBox().SelectedIndex = 0;

        }
        private void ucOrgTreeview_TreeViewAfterSelect(TreeNode node)
        {
            try
            {
                if (IsProcessing)
                {
                    return;
                }
                else
                {
                    IsProcessing = true;
                    this.Cursor = Cursors.WaitCursor;
                    //grbMainBase.Enabled = false;
                }

                TextBox txtYear = base.GetCommandByKey(TCMD_YEAR).GetTextBox();
                decimal year;
                bool isConvert = decimal.TryParse(txtYear.Text, out year);
                if (node != null && txtYear.Text.Trim().Length >= 4 && isConvert)
                {
                    //LoadTimePeriodByOrg(Convert.ToDecimal(node.Name), year);
                    //LoadGridData(false);
                    if (txtSearchEmp.Text.Trim() == string.Empty)
                        LoadGridData(false);
                    else LoadGridData(true);
                }

                IsProcessing = false;
                this.Cursor = Cursors.Default;
                //grbMainBase.Enabled = true;
            }
            catch (Exception ex)
            {
                IsProcessing = false;
                this.Cursor = Cursors.Default;
                //grbMainBase.Enabled = true;

                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
        }

        private void LoadTimePeriodByOrg(decimal year)
        {
            int periodSelected = 0;
            UICommand command = base.GetCommandByKey(DDCMD_TIMEPERIOD);
            ERP_SY_ORGPERIOD objSearch = new ERP_SY_ORGPERIOD();
            bool isSearch = false;
            objSearch.ID_ORG = (decimal?)base.GetCommandByKey(DDCMD_SITE).GetUIComboBox().SelectedValue;
            objSearch.YEAR = year;

            //if (command != null)
            //{
            //    objSearch.PERIOD_ID = (decimal?)command.GetUIComboBox().SelectedValue;
            //    if (command.GetUIComboBox().SelectedIndex >= 0)
            //        periodSelected = ((ERP_SY_ORGPERIOD)command.GetUIComboBox().SelectedItem.DataRow).ENDDATE.Month;
            //}

            _lstOrgPeriod = OracleHelper.ExcuteSelectMultiObject<ERP_SY_ORGPERIOD>("pkg_hcm_list", "PRS_ACTIVEORGPERIOD", objSearch);
            base.SetDataSourceToDropdownCommand(DDCMD_TIMEPERIOD, _lstOrgPeriod, "PERIODNAME", "PERIOD_ID", true);

            //if (_lstOrgPeriod.Count > 0)
            //{
            //    if (command != null)
            //    {
            //        command.GetUIComboBox().SelectedIndex = 0;
            //        if (periodSelected == 0)
            //            periodSelected = DateTime.Now.Month;
            //        for (int i = 0; i < _lstOrgPeriod.Count - 1; i++)
            //        {
            //            if (_lstOrgPeriod[i].ENDDATE.Month >= periodSelected && _lstOrgPeriod[i].STATUSCOLEX == (int)ColexStatus.Working)
            //            {
            //                command.GetUIComboBox().SelectedIndex = i;
            //                isSearch = true;
            //                break;
            //            }

            //        }
            //        if (!isSearch)
            //        {
            //            for (int i = _lstOrgPeriod.Count - 1; i >= 0; i--)
            //            {
            //                if (_lstOrgPeriod[i].ENDDATE.Month < periodSelected && _lstOrgPeriod[i].STATUSCOLEX == (int)ColexStatus.Working)
            //                {
            //                    command.GetUIComboBox().SelectedIndex = i;
            //                    break;
            //                }
            //            }
            //        }
            //    }

            //    //LoadGridData(false);
            //}
            //else
            //{
            //    base.GetCommandByKey(CommandBarManager.ActionCommand.Delete).Enabled = Janus.Windows.UI.InheritableBoolean.False;
            //    base.GetCommandByKey(CommandBarManager.ActionCommand.Save).Enabled = Janus.Windows.UI.InheritableBoolean.False;
            //}
        }

        //private DynamicEntityList LoadData(string empid, string emplst)
        private DataTable LoadData(string empid, string emplst)
        {
            //DynamicEntityList lstSwipeData;
            DataSet lstSwipeData;
            CO_SUM_SEARCH objSearch = new CO_SUM_SEARCH();
            objSearch.ORGID = ucOrgTreeview.OrgId;
            objSearch.PERIODID = (decimal?)base.GetCommandByKey(DDCMD_TIMEPERIOD).GetUIComboBox().SelectedValue;
            objSearch.DORGID = (decimal?)base.GetCommandByKey(DDCMD_SITE).GetUIComboBox().SelectedValue;
            //objSearch.Username = StaticObject.Username;
            objSearch.EMPLOYEEID = empid;
            objSearch.EMPLIST = emplst;

            lstSwipeData = OracleHelper.ExcuteSelectDataSet("PKG_HCM_COLEX", "PRS_INOUTVAL", objSearch);

            DataColor = LoadColor(empid, emplst);

            return (lstSwipeData != null && lstSwipeData.Tables.Count > 0) ? lstSwipeData.Tables[0] : null;
        }

        public List<CO_COLOR_OBJECT> LoadColor(string empid, string emplst)
        {
            List<CO_COLOR_OBJECT> lstSwipeDataColor;
            CO_SUM_SEARCH objSearch = new CO_SUM_SEARCH();
            objSearch.ORGID = ucOrgTreeview.OrgId;
            objSearch.PERIODID = (decimal?)base.GetCommandByKey(DDCMD_TIMEPERIOD).GetUIComboBox().SelectedValue;
            objSearch.DORGID = (decimal?)base.GetCommandByKey(DDCMD_SITE).GetUIComboBox().SelectedValue;
            //objSearch.Username = StaticObject.Username;
            objSearch.EMPLOYEEID = empid;
            objSearch.EMPLIST = emplst;

            lstSwipeDataColor = OracleHelper.ExcuteSelectMultiObject<CO_COLOR_OBJECT>(PKG_HCM_COLEX.NAME, PKG_HCM_COLEX.PRS_INOUTVALCOLOR, objSearch);
            return lstSwipeDataColor;
        }

        private void LoadGridData(bool isLoadByEmp)
        {
            ERP_SY_ORGPERIOD SelectedPeriod;
            //List<CO_SWIPE_DATA> lstSwipeData;
            //DynamicEntityList lstSwipeData;
            DataTable lstSwipeData;
            decimal periodid = (decimal)base.GetCommandByKey(DDCMD_TIMEPERIOD).GetUIComboBox().SelectedValue;
            if (isLoadByEmp)
            {
                lstSwipeData = LoadData(txtSearchEmp.Text.Trim(), string.Empty);
            }
            else
            {
                lstSwipeData = LoadData(string.Empty, string.Empty);
            }

            //if (lstSwipeData != null)
            //{
            //InitGrid();

            //lstSwipeData = OracleHelper.ExcuteSelectMultiObject<CO_SWIPE_DATA>(PKG_HCM_COLEX.NAME, PKG_HCM_COLEX.PRS_INOUTVAL, objSearch);
            //lstSwipeData = OracleHelper.ExcuteSelectMultiDynamicObject(PKG_HCM_COLEX.NAME, PKG_HCM_COLEX.PRS_INOUTVAL, objSearch);
            //lstDynEmpNoData = LoadEmployeeNoData(isLoadByEmp);
            //if (lstDynEmpNoData != null) lstDynObj.AddRange(lstDynEmpNoData);

            jgridData.SetDataBinding(lstSwipeData, "");

            //jgridData.
            SelectedPeriod = _lstOrgPeriod.Find(o => o.PERIOD_ID == periodid);
            ColexStatus status = ColexStatus.FinalClose;
           // if (SelectedPeriod != null)
               // status = (ColexStatus)SelectedPeriod.STATUSCOLEX;

            switch (status)
            {
                case ColexStatus.Working:
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Delete)).Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Save)).Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.ImportExcel)).Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    //base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.ImportAnotherFile)).Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    break;
                case ColexStatus.Close:
                case ColexStatus.FinalClose:
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Delete)).Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Save)).Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.ImportExcel)).Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    //base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.ImportAnotherFile)).Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    break;
                default:
                    break;
            }
            //}
            //else
            //{
            //    SetToolStripButtonBar(CommandBarManager.ActionCommand.Null);
            //}
        }

        private void InitGrid()
        {
            jgridData.RootTable.RemoveFilter();

            GridEXColumn col;
            
            jgridData.FrozenColumns = 4;
            jgridData.RootTable.Columns.Clear();
            col = new GridEXColumn();
            col.ActAsSelector = true;
            col.ColumnType = ColumnType.CheckBox;
            col.EditType = EditType.CheckBox;
            col.FilterEditType = FilterEditType.CheckBox;
            col.Width = 20;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_EMPLOYEEID;
            col.DataMember = GCOL_EMPLOYEEID;
            col.Caption = "MÃ NHÂN VIÊN";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.ColumnType = ColumnType.Text;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 80;
            //col.Selectable = false;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_EMPLOYEENAME;
            col.DataMember = GCOL_EMPLOYEENAME;
            col.Caption = "TÊN NHÂN VIÊN";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.ColumnType = ColumnType.Text;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 150;
            //col.Selectable = false;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_ORGNAME;
            col.DataMember = GCOL_ORGNAME;
            col.Caption = "Phòng ban / bộ phận";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.TextBox;
            col.ColumnType = ColumnType.Text;
            col.HeaderAlignment = TextAlignment.Center;
            col.Width = 150;
            //col.Selectable = false;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_WORKINGDAY;
            col.DataMember = GCOL_WORKINGDAY;
            col.Caption = "NGÀY";
            col.EditType = EditType.NoEdit;
            col.FilterEditType = FilterEditType.CalendarCombo;
            col.HeaderAlignment = TextAlignment.Center;
            col.TextAlignment = TextAlignment.Center;
            col.FormatString = Constant.FORMAT_DATE;
            col.Width = 100;
            jgridData.RootTable.Columns.Add(col);

            decimal colNo;
            CO_CONFIG_MNG fnCurrent = StaticObject.ConfigManager.Find(obj => obj.ID == ConfigManagerKey.SWIPEDATA_GCOL);
            string cfCurrentColumn = fnCurrent == null ? "0" : fnCurrent.Value;
            bool result = Decimal.TryParse(cfCurrentColumn, out colNo);
            if (result)
            {
                for (int idx = 1; idx <= colNo; idx++)
                {
                    col = new GridEXColumn();
                    col.Key = GCOL_PREFIX_DATA_VALIN + idx.ToString();
                    col.DataMember = GCOL_PREFIX_DATA_VALIN + idx.ToString();
                    col.Caption = GCOL_PREFIX_CAPTION_VALIN + idx.ToString();
                    col.HeaderStyle.TextAlignment = TextAlignment.Center;
                    col.EditType = EditType.TextBox;
                    col.TextAlignment = TextAlignment.Center;
                    col.FilterEditType = FilterEditType.SameAsEditType;
                    col.InputMask = "##:##";
                    col.Width = 80;
                    col.HeaderToolTip = GCOL_PREFIX_CAPTION_VALIN + idx.ToString();
                    col.DefaultValue = string.Empty;
                    jgridData.RootTable.Columns.Add(col);

                    col = new GridEXColumn();
                    col.Key = GCOL_PREFIX_DATA_VALOUT + idx.ToString();
                    col.DataMember = GCOL_PREFIX_DATA_VALOUT + idx.ToString();
                    col.Caption = GCOL_PREFIX_CAPTION_VALOUT + idx.ToString();
                    col.HeaderStyle.TextAlignment = TextAlignment.Center;
                    col.EditType = EditType.TextBox;
                    col.TextAlignment = TextAlignment.Center;
                    col.FilterEditType = FilterEditType.SameAsEditType;
                    col.InputMask = "##:##";
                    col.Width = 80;
                    col.HeaderToolTip = GCOL_PREFIX_CAPTION_VALOUT + idx.ToString();
                    col.DefaultValue = string.Empty;
                    jgridData.RootTable.Columns.Add(col);
                }
            }

            col = new GridEXColumn();
            col.Key = GCOL_ID;
            col.DataMember = GCOL_ID;
            col.Visible = false;
            col.EditType = EditType.NoEdit;
            //col.Selectable = false;
            jgridData.RootTable.Columns.Add(col);

            col = new GridEXColumn();
            col.Key = GCOL_STATUS;
            col.DataMember = GCOL_STATUS;
            col.Visible = false;
            col.EditType = EditType.NoEdit;
            //col.Selectable = false;
            jgridData.RootTable.Columns.Add(col);
        }

        private bool DeleteDataById(decimal id)
        {
            CO_DAY_RGT objDel = new CO_DAY_RGT();
            objDel.ID = id;

            OracleHelper.ExcuteNonQuery("PKG_HCM_COLEX", "PRD_INOUTVAL", objDel);

            return true;
        }

        private void jgridData_FormattingRow(object sender, RowLoadEventArgs e)
        {
            decimal id;
            string backgroundvalue = Constant.COLOR_WHITE;
            string forevalue = Constant.COLOR_BLACK;
            Janus.Windows.GridEX.GridEXFormatStyle formatStyle;
            CO_COLOR_OBJECT objSelected;
            try
            {
                id = Convert.ToDecimal(e.Row.Cells[GCOL_ID].Value);
                objSelected = DataColor.Find(obj => obj.ID == id);
                if (objSelected != null)
                {
                    if (!String.IsNullOrEmpty(objSelected.BGCOLOR))
                    {
                        backgroundvalue = objSelected.BGCOLOR.Split(',')[0];
                    }

                    if (!String.IsNullOrEmpty(objSelected.FRCOLOR))
                    {
                        forevalue = objSelected.FRCOLOR.Split(',')[0];
                    }

                    formatStyle = new Janus.Windows.GridEX.GridEXFormatStyle();
                    formatStyle.BackColor = System.Drawing.ColorTranslator.FromHtml(backgroundvalue);
                    formatStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml(forevalue);
                    e.Row.RowStyle = formatStyle;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message + ex.StackTrace);
                Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
        }

        private void txtSearchEmp_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                if (txtSearchEmp.Text.Trim() != string.Empty)
                    LoadGridData(true);
                else LoadGridData(false);
            }
        }

        protected override bool CommandValueChanged(Janus.Windows.UI.CommandBars.UICommand Command)
        {
            TextBox txtYear;
            decimal year;
            bool isConvert;
            switch (Command.Key)
            {
                case DDCMD_SITE:
                case TCMD_YEAR:
                    txtYear = base.GetCommandByKey(TCMD_YEAR).GetTextBox();
                    isConvert = decimal.TryParse(txtYear.Text, out year);

                    if (txtYear.Text.Trim().Length >= 4 & isConvert)
                    {
                        LoadTimePeriodByOrg(year);
                        if (txtSearchEmp.Text.Trim() == string.Empty)
                            LoadGridData(false);
                        else LoadGridData(true);
                    }
                    break;

                case DDCMD_TIMEPERIOD:
                    txtYear = base.GetCommandByKey(TCMD_YEAR).GetTextBox();
                    isConvert = decimal.TryParse(txtYear.Text, out year);

                    if (txtYear.Text.Trim().Length >= 4 & isConvert)
                    {
                        if (txtSearchEmp.Text.Trim() == string.Empty)
                            LoadGridData(false);
                        else LoadGridData(true);
                    }
                    break;

                default:
                    break;
            }
            return true;
        }

        protected override bool DeleteButtonClick()
        {
            DialogResult dlgResult;

            if (jgridData.GetCheckedRows().Length > 0)
            {
                dlgResult = MessageBox.Show(Constant.MSG_DELINOUTVAL_CFM,
                                            this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlgResult == DialogResult.Yes)
                {
                    foreach (var item in jgridData.GetCheckedRows())
                    {
                        DeleteDataById(Convert.ToDecimal(item.Cells[GCOL_ID].Value));
                    }

                    if (txtSearchEmp.Text.Trim() == string.Empty)
                        LoadGridData(false);
                    else LoadGridData(true);
                }
            }

            return false;
        }

        protected override bool SaveButtonClick()
        {
            StringBuilder cmdBuilder;
            CO_SWIPE_DATA objUpd;
            decimal colNo;
            CO_CONFIG_MNG fnCurrent;
            string cfCurrentColumn;
            bool result;
            TimeSpan tspValue = TimeSpan.Zero;
            TimeSpan tspCurValue = TimeSpan.Zero;
            string cellvalue;
            string[] cellsplit;
            int addDay = 0;
            if (jgridData.GetCheckedRows().Count() == 0)
            {
                MessageBox.Show("Yêu cầu chọn nhân viên muốn lưu dữ liệu", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            foreach (var jdtRow in jgridData.GetCheckedRows())
            {
                jdtRow.BeginEdit();
                if (jdtRow.Cells[GCOL_STATUS].Value != null &&
                    jdtRow.Cells[GCOL_STATUS].Value.ToString() != "0")
                {
                    objUpd = new CO_SWIPE_DATA();
                    if (jdtRow.Cells[GCOL_ID].Value != null
                        && jdtRow.Cells[GCOL_ID].Value.ToString() != string.Empty)
                    {
                        objUpd.ID = Convert.ToDecimal(jdtRow.Cells[GCOL_ID].Value);
                    }

                    objUpd.EMPLOYEEID = jdtRow.Cells[GCOL_EMPLOYEEID].Value.ToString();
                    objUpd.WORKINGDAY = Convert.ToDateTime(jdtRow.Cells[GCOL_WORKINGDAY].Value);

                    cmdBuilder = new StringBuilder();
                    fnCurrent = StaticObject.ConfigManager.Find(obj => obj.ID == ConfigManagerKey.SWIPEDATA_GCOL);
                    cfCurrentColumn = fnCurrent == null ? "0" : fnCurrent.Value;
                    result = Decimal.TryParse(cfCurrentColumn, out colNo);
                    tspValue = TimeSpan.Zero;
                    if (result)
                    {
                        for (int idx = 1; idx <= colNo; idx++)
                        {
                            if (jdtRow.Cells[GCOL_PREFIX_DATA_VALIN + idx.ToString()].Value != null
                                && jdtRow.Cells[GCOL_PREFIX_DATA_VALIN + idx.ToString()].Value.ToString() != string.Empty)
                            {
                                cellvalue = jdtRow.Cells[GCOL_PREFIX_DATA_VALIN + idx.ToString()].Value.ToString();
                                cellsplit = cellvalue.Split(':');
                                if (cellsplit.Length == 2)
                                {
                                    tspCurValue = new TimeSpan(Convert.ToInt32(cellsplit[0]), Convert.ToInt32(cellsplit[1]), 0);
                                    if (tspCurValue < tspValue)
                                    {
                                        addDay = 1;

                                    }
                                    else
                                    {
                                        addDay = 0;
                                        tspValue = tspCurValue;
                                    }

                                    cmdBuilder.AppendLine(string.Format(COMMAND_UPDATEVALUE,
                                                       GCOL_PREFIX_DATA_VALIN + idx.ToString(),
                                                       objUpd.WORKINGDAY.Value.AddDays(addDay).Add(tspCurValue).ToString(Constant.FORMAT_DATETIME)));
                                }

                                
                            }
                            else
                            {
                                cmdBuilder.AppendLine(string.Format(COMMAND_UPDATENULLVALUE,
                                                       GCOL_PREFIX_DATA_VALIN + idx.ToString()));
                            }

                            if (jdtRow.Cells[GCOL_PREFIX_DATA_VALOUT + idx.ToString()].Value != null
                               && jdtRow.Cells[GCOL_PREFIX_DATA_VALOUT + idx.ToString()].Value.ToString() != string.Empty)
                            {
                                cellvalue = jdtRow.Cells[GCOL_PREFIX_DATA_VALOUT + idx.ToString()].Value.ToString();
                                cellsplit = cellvalue.Split(':');
                                if (cellsplit.Length == 2)
                                {
                                    tspCurValue = new TimeSpan(Convert.ToInt32(cellsplit[0]), Convert.ToInt32(cellsplit[1]), 0);
                                    if (tspCurValue < tspValue)
                                    {
                                        addDay = 1;

                                    }
                                    else
                                    {
                                        addDay = 0;
                                        tspValue = tspCurValue;
                                    }
                                    cmdBuilder.AppendLine(string.Format(COMMAND_UPDATEVALUE,
                                                       GCOL_PREFIX_DATA_VALOUT + idx.ToString(),
                                                       objUpd.WORKINGDAY.Value.AddDays(addDay).Add(tspCurValue).ToString(Constant.FORMAT_DATETIME)));
                                }

                                //cmdBuilder.AppendLine(string.Format(COMMAND_UPDATEVALUE,
                                //                     GCOL_PREFIX_DATA_VALOUT + idx.ToString(),
                                //                     objUpd.WORKINGDAY.Value.AddDays(addDay).ToString(Constant.FORMAT_DATE) + " " + cellvalue));
                            }
                            else
                            {
                                cmdBuilder.AppendLine(string.Format(COMMAND_UPDATENULLVALUE,
                                                      GCOL_PREFIX_DATA_VALOUT + idx.ToString()));
                            }
                        }

                        objUpd.COMMAND = cmdBuilder.ToString();
                        //objUpd.Username = StaticObject.Username;
                    }

                    OracleHelper.ExcuteNonQuery("PKG_HCM_COLEX", "PRU_INOUTVAL", objUpd);

                    jdtRow.Cells[GCOL_STATUS].Value = 0;
                }
                jdtRow.EndEdit();
            }
            MessageBox.Show(Constant.MSG_TRANSACTION_SUCCESSFUL, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (jgridData.GetCheckedRows().Length > 0)
            {
                if (txtSearchEmp.Text.Trim() == string.Empty)
                    DataColor = LoadColor(string.Empty, string.Empty);
                else DataColor = LoadColor(txtSearchEmp.Text.Trim(), string.Empty);
                jgridData.UnCheckAllRecords();
                jgridData.Refetch();
            }

            return false;
        }

        protected override bool AddNewButtonClick()
        {
            StringBuilder emplst = new StringBuilder();
            //DynamicEntityList lstSwipeData;
            DataTable lstSwipeData;
            List<EMPLOYEE_SELECTION> lstSelection = new List<EMPLOYEE_SELECTION>();
            EMPLOYEE_SELECTION objSelection;
            UICommand command;
            foreach (var item in jgridData.GetCheckedRows())
            {
                objSelection = new EMPLOYEE_SELECTION();
                objSelection.EMPLOYEEID = item.Cells[GCOL_EMPLOYEEID].Value.ToString();
                objSelection.EMPLOYEENAME = item.Cells[GCOL_EMPLOYEENAME].Value.ToString();
                if (lstSelection.Find(s => s.EMPLOYEEID == objSelection.EMPLOYEEID) != null)
                {
                    continue;
                }
                lstSelection.Add(objSelection);
            }

            //frmSwipeDataRegister frmRgt = new frmSwipeDataRegister();
            //frmRgt.ListEmployeeRegist = lstSelection;
            //frmRgt.ShowDialog();

            //if (frmRgt.RegisterResult == DialogResult.OK)
            //{
            //    txtSearchEmp.Text = string.Empty;
            //    command = base.GetCommandByKey(DDCMD_TIMEPERIOD);

            //    for (int i = _lstOrgPeriod.Count - 1; i >= 0; i--)
            //    {
            //        if (frmRgt.FromDate >= _lstOrgPeriod[i].STARTDATE && frmRgt.FromDate <= _lstOrgPeriod[i].ENDDATE)
            //        {
            //            command.GetUIComboBox().SelectedIndex = i;
            //            break;
            //        }
            //    }

            ////    foreach (var itmEmpRgt in frmRgt.ListEmployeeRegist)
            ////    {
            ////        emplst.Append(itmEmpRgt.EMPLOYEEID + ",");
            ////    }

            ////    lstSwipeData = LoadData(string.Empty, emplst.ToString());
            ////    jgridData.SetDataBinding(lstSwipeData, "");

            //}

            return false;
        }

        protected override bool ImportExcelButtonClick()
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "XML Spreadsheet 2003 (*.xml)|*.xml";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                if (IOCommonFunction.FileInUse(openDialog.FileName))
                {
                    MessageBox.Show(string.Format(Constant.MSG_CANNOT_OPENFILE, openDialog.FileName),
                                    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }

                //InitGrid();

                Aspose.Cells.License lc = new Aspose.Cells.License();
                string strLicense = AppDomain.CurrentDomain.BaseDirectory + "\\lib\\Aspose.Cells.lic";
                lc.SetLicense(strLicense);

                //Instantiate LoadOptions specified by the LoadFormat.
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                //workbook.ConvertNumericData = false;
                workbook.Open(openDialog.FileName);

                Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
                DataTable mv_dtDataPrepare = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow + 1, worksheet.Cells.MaxColumn + 1);

                DataRow dtRowTitle = mv_dtDataPrepare.Rows[0];
                foreach (GridEXColumn gCol in jgridData.RootTable.Columns)
                {
                    foreach (DataColumn dtCol in mv_dtDataPrepare.Columns)
                    {
                        if (gCol.Caption != string.Empty &&
                            dtRowTitle[dtCol].ToString() != string.Empty &&
                            gCol.Caption.Equals(dtRowTitle[dtCol]))
                        {
                            dtCol.ColumnName = gCol.Key;
                            if (gCol.DataMember.StartsWith(GCOL_PREFIX_CAPTION_VALIN) ||
                                gCol.DataMember.StartsWith(GCOL_PREFIX_CAPTION_VALOUT))
                            {
                                dtCol.DataType = typeof(DateTime);
                                dtCol.DateTimeMode = DataSetDateTime.Local;
                            }
                            break;
                        }
                    }
                }

                //remove first row is header row
                mv_dtDataPrepare.Rows.RemoveAt(0);
                //remove colunms null
                for(int i = 0; i < mv_dtDataPrepare.Rows.Count; i++)
                {
                    if (mv_dtDataPrepare.Rows[i][GCOL_EMPLOYEEID] == DBNull.Value)
                        mv_dtDataPrepare.Rows.RemoveAt(i);
                }
                //jgridData.SetDataBinding(mv_dtDataPrepare, string.Empty);
                DataColumn dcolStatus = new DataColumn();
                dcolStatus.ColumnName = GCOL_STATUS;
                dcolStatus.DataType = typeof(int);
                dcolStatus.DefaultValue = 1;

                mv_dtDataPrepare.Columns.Add(dcolStatus);

                dwDataPrepare = mv_dtDataPrepare.DefaultView;
                dwDataPrepare.Sort = GCOL_WORKINGDAY;
                DateTime impMinDate = Convert.ToDateTime(dwDataPrepare[0][GCOL_WORKINGDAY]);
                DateTime impMaxDate = Convert.ToDateTime(dwDataPrepare[dwDataPrepare.Count - 1][GCOL_WORKINGDAY]);

                UICommand command = base.GetCommandByKey(DDCMD_TIMEPERIOD);
                ERP_SY_ORGPERIOD objCheck;
                if (command != null)
                {
                    objCheck = (ERP_SY_ORGPERIOD)command.GetUIComboBox().SelectedItem.DataRow;
                    //if (!(impMinDate.Date >= objCheck.STARTDATE.GetValueOrDefault(impMinDate.Date).Date
                    //   && impMinDate.Date <= objCheck.ENDDATE.Date
                    //   && impMaxDate.Date >= objCheck.STARTDATE.GetValueOrDefault(impMaxDate.Date).Date
                    //   && impMaxDate.Date <= objCheck.ENDDATE.Date))
                    //{
                    //    MessageBox.Show(MSG_INVALID_PERIOD, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //    return false;
                    //}
                }

                jgridData.DataSource = mv_dtDataPrepare;
                jgridData.Refresh();

                int outval;
                string[] value;
                foreach (var jgdRow in jgridData.GetDataRows())
                {
                    jgdRow.BeginEdit();
                    foreach (GridEXCell jgdCell in jgdRow.Cells)
                    {
                        if (jgdCell.Column.Key.StartsWith(GCOL_PREFIX_DATA_VALIN) ||
                            jgdCell.Column.Key.StartsWith(GCOL_PREFIX_DATA_VALOUT))
                        {
                            if (jgdCell.Value == null || jgdCell.Value.ToString() == string.Empty)
                                continue;

                            value = jgdCell.Value.ToString().Split(':');

                            if (value.Length != 2)
                            {
                                jgdCell.Value = string.Empty;
                                continue;
                            }

                            if (value[0] == string.Empty) value[0] = "00";
                            if (value.Length > 1 && value[1] == string.Empty) value[1] = "00";

                            if (!(int.TryParse(value[0], out outval) &&
                                outval >= 0 && outval < 24))
                            {
                                jgdCell.Value = string.Empty;
                                continue;
                            }
                            else
                            {
                                value[0] = value[0].Length < 2 ? "0" + value[0] : value[0];
                            }

                            if (!(int.TryParse(value[1], out outval) && outval >= 0 && outval <= 59))
                            {
                                jgdCell.Value = string.Empty;
                                continue;
                            }
                            else
                            {
                                value[1] = value[1].Length < 2 ? "0" + value[1] : value[1];
                            }

                            jgdCell.Value = value[0] + ":" + value[1];
                        }
                    }
                    jgdRow.EndEdit();
                }
            }

            return true;
        }

        protected override bool ImportAnotherFileButtonClick()
        {
            //DateTime impMinDate;
            //DateTime impMaxDate;
            ////List<CO_SWIPE_DATA> objLstUpd = new List<CO_SWIPE_DATA>();
            //CO_SWIPE_DATA objUpd = new CO_SWIPE_DATA();
            //OpenFileDialog openDialog = new OpenFileDialog();
            //openDialog.Filter = "ACV Text File(*.txt)|*.txt";
            //DataColumn colUpd;
            //if (openDialog.ShowDialog() == DialogResult.OK)
            //{
            //    if (IOCommonFunction.FileInUse(openDialog.FileName))
            //    {
            //        MessageBox.Show(string.Format(Constant.MSG_CANNOT_OPENFILE, openDialog.FileName),
            //                        this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //        return false;
            //    }

            //    this.Cursor = Cursors.WaitCursor;

            //    Aspose.Cells.License lc = new Aspose.Cells.License();
            //    string strLicense = AppDomain.CurrentDomain.BaseDirectory + "\\lib\\Aspose.Cells.lic";
            //    lc.SetLicense(strLicense);

            //    //Instantiate LoadOptions specified by the LoadFormat.
            //    Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            //    workbook.Open(openDialog.FileName, Aspose.Cells.FileFormatType.TabDelimited);

            //    Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
            //    DataTable dtDataPrepare = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow + 1, worksheet.Cells.MaxColumn + 1);

            //    if (dtDataPrepare.Rows.Count <= 0)
            //    {
            //        MessageBox.Show(Constant.MSG_NOTHAVE_IMPDATA, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //        return false;
            //    }

            //    colUpd = new DataColumn(DTCOL_UPDATE, typeof(int));
            //    colUpd.DefaultValue = 0;
            //    dtDataPrepare.Columns.Add(colUpd);

            //    colUpd = new DataColumn(DTCOL_TRUEVALUE, typeof(DateTime));
            //    colUpd.Expression = "Convert(SubString(Convert(Column4,'System.String'),1,10) +' '+ SubString(Convert(Column5,'System.String'),12,8),'System.DateTime')";
            //    dtDataPrepare.Columns.Add(colUpd);

            //    dwDataPrepare = dtDataPrepare.DefaultView;
            //    dwDataPrepare.Sort = "Column4";
            //    impMinDate = Convert.ToDateTime(dwDataPrepare[0]["Column4"]);
            //    impMaxDate = Convert.ToDateTime(dwDataPrepare[dwDataPrepare.Count - 1]["Column4"]);

            //    UICommand command = base.GetCommandByKey(DDCMD_TIMEPERIOD);
            //    ERP_SY_ORGPERIOD objCheck;
            //    if (command != null)
            //    {
            //        objCheck = (ERP_SY_ORGPERIOD)command.GetUIComboBox().SelectedItem.DataRow;
            //        if (!(impMinDate.Date >= objCheck.STARTDATE.GetValueOrDefault(impMinDate.Date).Date
            //           && impMinDate.Date <= objCheck.ENDDATE.Date
            //           && impMaxDate.Date >= objCheck.STARTDATE.GetValueOrDefault(impMaxDate.Date).Date
            //           && impMaxDate.Date <= objCheck.ENDDATE.Date))
            //        {
            //            MessageBox.Show(MSG_INVALID_PERIOD, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //            return false;
            //        }
            //    }

            //    ExcuteAsynchronous();

            //    this.Cursor = Cursors.Default;
            //}
            UICommand command = base.GetCommandByKey(DDCMD_TIMEPERIOD);

            //frmImpRange = new frmSwipeDateRangeImport();
            //frmImpRange.OrgId = ucOrgTreeview.OrgId;
            //frmImpRange.OrgName = ucOrgTreeview.OrgName;
            //frmImpRange.SelectedPeriod = (ERP_SY_ORGPERIOD)command.GetUIComboBox().SelectedItem.DataRow;
            //DialogResult result = frmImpRange.ShowDialog();

            //if (result == DialogResult.OK)
            //{
            //    _isOverrideData = frmImpRange.IsOverrideData;
            //    dwDataPrepare = frmImpRange.DataPrepare;

            //    ExcuteAsynchronous();
            //}

            return true;
        }

        protected override bool AsynchronousFunctionWithBGW(BackgroundWorker bgWorker)
        {
            CO_SWIPE_DATA objUpd;
            StringBuilder cmdBuilder;
            List<CO_DAY_RGT> lstEmpInPeriod;
            CO_DAY_RGT objSearch;
            List<CO_SWIPE_DATA> lstUpd;
            List<CO_SWIPE_DATA> objLstUpd = new List<CO_SWIPE_DATA>();
            DataTable dtEmpLstDate;
            DateTime swipeval = DateTime.MinValue;
            int idxCheckData = 0;
            TimeSpan spVal;
            int inidx = 0;
            int outidx = 0;
            int inoutkey = 0;
            DateTime starttime;
            DateTime endtime;
            CO_SIGN_LST ShiftSearch;
            List<CO_SIGN_LST> lstShiftCode;
            try
            {
                dwDataPrepare.RowStateFilter = DataViewRowState.CurrentRows;
                starttime = DateTime.Now;
                bgWorker.ReportProgress(0, "Đang kiểm tra và xử lý dữ liệu. Xin vui lòng đợi...");

                dtEmpLstDate = dwDataPrepare.ToTable(true, "Column2", "Column4");
                foreach (DataRow drEmpLst in dtEmpLstDate.Rows)
                {
                    objUpd = new CO_SWIPE_DATA();
                    objUpd.EMPLOYEEID = drEmpLst["Column2"].ToString();
                    objUpd.WORKINGDAY = Convert.ToDateTime(drEmpLst["Column4"]).Date;
                    objLstUpd.Add(objUpd);
                }

                objLstUpd = objLstUpd.OrderBy(x => x.EMPLOYEEID).ThenBy(x => x.WORKINGDAY).ToList();

                dwDataPrepare.Sort = DTCOL_TRUEVALUE;

                lstShiftCode = StaticObject.LstAllSign.FindAll(obj => !string.IsNullOrEmpty(obj.SHIFTCODE));

                foreach (CO_SWIPE_DATA itmEmpLst in objLstUpd)
                {
                    bgWorker.ReportProgress(idxCheckData * 100 / objLstUpd.Count, string.Format(MSG_PROCESSING_RECORDS, itmEmpLst.EMPLOYEEID, itmEmpLst.WORKINGDAY.Value.ToString(Constant.FORMAT_DATE), idxCheckData * 100 / objLstUpd.Count));

                    cmdBuilder = new StringBuilder();
                    inidx = 0;
                    outidx = 0;

                    dwDataPrepare.RowFilter = string.Format(CultureInfo.InvariantCulture.DateTimeFormat,
                                                            FILLTER_EMPWRK,
                                                            itmEmpLst.EMPLOYEEID,
                                                            itmEmpLst.WORKINGDAY.Value,
                                                            itmEmpLst.WORKINGDAY.Value.AddDays(1));
                    swipeval = DateTime.MinValue;
                    foreach (DataRowView drImp in dwDataPrepare)
                    {
                        //Neu quet the 2 lan trong 5p thi khong tinh
                        if (swipeval != DateTime.MinValue &&
                           (swipeval.AddMinutes(5) >= Convert.ToDateTime(drImp[DTCOL_TRUEVALUE]) &&
                            swipeval.AddMinutes(-5) <= Convert.ToDateTime(drImp[DTCOL_TRUEVALUE])) &&
                            inoutkey == Convert.ToInt32(drImp["Column3"]))
                        {
                            drImp[DTCOL_UPDATE] = 1;
                            continue;
                        }

                        swipeval = Convert.ToDateTime(drImp[DTCOL_TRUEVALUE]);
                        inoutkey = Convert.ToInt32(drImp["Column3"]);
                        //Xu ly du lieu trong ngay
                        if (itmEmpLst.WORKINGDAY.Value.Date == swipeval.Date)
                        {
                            //XU LY DU LIEU VAO
                            if (inoutkey == 1)
                            {
                                if (outidx > inidx)
                                    inidx = outidx + 1;
                                else inidx++;

                                cmdBuilder.AppendLine(string.Format(COMMAND_UPDATEVALUE,
                                                                    GCOL_PREFIX_DATA_VALIN + inidx.ToString(),
                                                                    swipeval.ToString(Constant.FORMAT_DATETIME)));
                            }

                            //XU LY DU LIEU RA
                            if (inoutkey == 0)
                            {
                                if (outidx < inidx)
                                    outidx = inidx;
                                else outidx++;

                                cmdBuilder.AppendLine(string.Format(COMMAND_UPDATEVALUE,
                                                                    GCOL_PREFIX_DATA_VALOUT + outidx.ToString(),
                                                                    swipeval.ToString(Constant.FORMAT_DATETIME)));
                            }

                            drImp[DTCOL_UPDATE] = 1;
                        } //Xu lu du lieu ca dem
                        else if (itmEmpLst.WORKINGDAY.Value.AddDays(1).Date == swipeval.Date)
                        {
                            if (inoutkey == 1) //Vao, ko tinh
                            {
                                break;
                            }

                            spVal = TimeSpan.MaxValue;
                            ShiftSearch = null;
                            foreach (CO_SIGN_LST iShift in lstShiftCode)
                            {
                                if (iShift.SHIFTOUT.Value.TimeOfDay.TotalMilliseconds != 0)
                                {
                                    if (swipeval.TimeOfDay > iShift.SHIFTOUT.Value.TimeOfDay)
                                    {
                                        if (spVal >= (swipeval.TimeOfDay - iShift.SHIFTOUT.Value.TimeOfDay))
                                        {
                                            spVal = swipeval.TimeOfDay - iShift.SHIFTOUT.Value.TimeOfDay;
                                            ShiftSearch = iShift;
                                        }
                                    }
                                    else
                                    {
                                        if (spVal >= (iShift.SHIFTOUT.Value.TimeOfDay - swipeval.TimeOfDay))
                                        {
                                            spVal = iShift.SHIFTOUT.Value.TimeOfDay - swipeval.TimeOfDay;
                                            ShiftSearch = iShift;
                                        }
                                    }
                                }
                            }

                            if (ShiftSearch != null && ShiftSearch.ISNIGHTSHIFT == 1)
                            {
                                if (outidx < inidx)
                                    outidx = inidx;
                                else outidx++;

                                cmdBuilder.AppendLine(string.Format(COMMAND_UPDATEVALUE,
                                                                    GCOL_PREFIX_DATA_VALOUT + outidx.ToString(),
                                                                    swipeval.ToString(Constant.FORMAT_DATETIME)));

                                drImp[DTCOL_UPDATE] = 1;
                            }
                        }

                        //drImp[DTCOL_UPDATE] = 1;
                    }

                    idxCheckData++;

                    itmEmpLst.COMMAND = cmdBuilder.ToString();
                }

                if (objLstUpd != null && objLstUpd.Count > 0)
                {
                    objSearch = new CO_DAY_RGT();
                   // objSearch.Username = StaticObject.Username;
                    objSearch.WORKINGDAY = objLstUpd.Min(obj => obj.WORKINGDAY);
                    objSearch.ENDDATE = objLstUpd.Max(obj => obj.WORKINGDAY);
                    objSearch.ORGID = ucOrgTreeview.OrgId;
                    lstEmpInPeriod = OracleHelper.ExcuteSelectMultiObject<CO_DAY_RGT>("PKG_HCM_COLEX","PRS_EMPINPERIOD", objSearch);

                    lstUpd = objLstUpd.Where(item => lstEmpInPeriod.Count(match => item.EMPLOYEEID.PadLeft(10, '0') == match.EMPLOYEEID.PadLeft(10, '0')) > 0).ToList();

                    for (int idx = 0; idx < lstUpd.Count; idx++)
                    {
                        //lstUpd[idx].Username = StaticObject.Username;
                        lstUpd[idx].OVERRIDEDATA = _isOverrideData ? 1 : 0;
                        OracleHelper.ExcuteNonQuery("PKG_HCM_COLEX", "PRU_IMPFROMACVFILE", lstUpd[idx]);

                        bgWorker.ReportProgress((idx + 1) * 100 / objLstUpd.Count, string.Format(MSG_UPDATE_RECORDS, objLstUpd[idx].EMPLOYEEID, objLstUpd[idx].WORKINGDAY.Value.ToString(Constant.FORMAT_DATE), (idx + 1) * 100 / objLstUpd.Count));
                    }

                    endtime = DateTime.Now;
                    bgWorker.ReportProgress(100, string.Format("Đã hoàn tất cập nhật dữ liệu của [{0}] bảng ghi({1}).", lstUpd.Count, (endtime - starttime).TotalMinutes));
                }

                dwDataPrepare.RowFilter = string.Empty;
                return true;
            }
            catch (Exception ex)
            {
                bgWorker.ReportProgress(0, ex.Message + ex.StackTrace);
                Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
                return false;
            }
        }

        protected override void RunAfterWorkerCompleted(bool result)
        {
            if (txtSearchEmp.Text.Trim() == string.Empty)
                LoadGridData(false);
            else LoadGridData(true);
        }

        private void jgridData_UpdatingCell(object sender, UpdatingCellEventArgs e)
        {
            try
            {
                int outval;
                if (!IsProcessing)
                {
                    IsProcessing = true;

                    if (e.Value != null && e.Value.ToString() != string.Empty)
                    {
                        string[] value = e.Value.ToString().Split(':');

                        if (value[0] == string.Empty) value[0] = "00";
                        if (value.Length > 1 && value[1] == string.Empty) value[1] = "00";

                        if (!(int.TryParse(value[0], out outval) &&
                            outval >= 0 && outval < 24))
                        {
                            e.Cancel = true;
                            return;
                        }
                        else
                        {
                            value[0] = value[0].Length < 2 ? "0" + value[0] : value[0];
                        }

                        if (value.Length > 1)
                        {
                            if (!(int.TryParse(value[1], out outval) &&
                                outval >= 0 && outval <= 59))
                            {
                                e.Cancel = true;
                                return;
                            }
                            else
                            {
                                value[1] = value[1].Length < 2 ? "0" + value[1] : value[1];
                            }
                        }

                        if (value.Length == 1 && value[0] == "00")
                        {
                            e.Value = null;
                        }
                        else
                        {
                            e.Value = value[0] + ":" + value[1];
                        }
                    }

                    jgridData.CurrentRow.Cells[GCOL_STATUS].Value = "1";
                    jgridData.CurrentRow.CheckState = RowCheckState.Checked;
                    IsProcessing = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void jgridData_CellUpdated(object sender, ColumnActionEventArgs e)
        {
            try
            {
                int editingindex;
                CO_CONFIG_MNG fnCurrent;
                if (!IsProcessing)
                {
                    IsProcessing = true;
                    if (!(jgridData.CurrentRow.Cells[e.Column].Value != null && jgridData.CurrentRow.Cells[e.Column].Value.ToString() != string.Empty))
                    {
                        fnCurrent = StaticObject.ConfigManager.Find(obj => obj.ID == ConfigManagerKey.SWIPEDATA_GCOL);
                        if (e.Column.Key.StartsWith(GCOL_PREFIX_DATA_VALIN))
                        {
                            editingindex = Convert.ToInt32(e.Column.Key.Substring(GCOL_PREFIX_DATA_VALIN.Length));
                            if (editingindex < Convert.ToInt32(fnCurrent.Value))
                            {
                                for (int idx = editingindex; idx < Convert.ToInt32(fnCurrent.Value); idx++)
                                {
                                    jgridData.CurrentRow.Cells[GCOL_PREFIX_DATA_VALIN + idx.ToString()].Value = jgridData.CurrentRow.Cells[GCOL_PREFIX_DATA_VALIN + (idx + 1).ToString()].Value;
                                    //((DataRowView)jgridData.CurrentRow.DataRow).Row[GCOL_PREFIX_DATA_VALIN + idx.ToString()] = ((DataRowView)jgridData.CurrentRow.DataRow).Row[GCOL_PREFIX_DATA_VALIN + (idx + 1).ToString()];
                                }
                            }
                        }
                        else if (e.Column.Key.StartsWith(GCOL_PREFIX_DATA_VALOUT))
                        {
                            editingindex = Convert.ToInt32(e.Column.Key.Substring(GCOL_PREFIX_DATA_VALOUT.Length));
                            if (editingindex < Convert.ToInt32(fnCurrent.Value))
                            {
                                for (int idx = editingindex; idx < Convert.ToInt32(fnCurrent.Value); idx++)
                                {
                                    jgridData.CurrentRow.Cells[GCOL_PREFIX_DATA_VALOUT + idx.ToString()].Value = jgridData.CurrentRow.Cells[GCOL_PREFIX_DATA_VALOUT + (idx + 1).ToString()].Value;
                                    //((DataRowView)jgridData.CurrentRow.DataRow).Row[GCOL_PREFIX_DATA_VALOUT + idx.ToString()] = ((DataRowView)jgridData.CurrentRow.DataRow).Row[GCOL_PREFIX_DATA_VALOUT + (idx+1).ToString()];
                                }
                            }
                        }
                    }
                    IsProcessing = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
